package com.examination.client.exception;

import com.examination.client.enums.ResultEnum;
import com.examination.client.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author: XiaoDong
 * @date: 2021-10-18 17:45
 * @description:
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler({Exception.class})
    @ResponseBody
    public Result processException(Exception ex, HttpServletResponse response) throws IOException {
        log.info(ex.getMessage());
        return Result.fail(ex.getMessage());
    }

    @ExceptionHandler({BusinessException.class})
    @ResponseBody
    public Result processRuntimeException(BusinessException ex) {
        return Result.fail(ex.getCode(), ex.getMsg());
    }

    @ExceptionHandler({RuntimeException.class})
    @ResponseBody
    public Result processRuntimeException(RuntimeException ex) {
        String msg = ex.getMessage();
        if (StringUtils.isEmpty(msg)) {
            msg = ResultEnum.FAIL.msg;
        }
        return Result.fail(ResultEnum.FAIL.code, msg);
    }

}
